import fetch from "cross-fetch";
import * as queryString from "query-string";
import cookie from "react-cookies";
import errorCode from "./errorCode";
import { history } from "@/redux/configStore";

const codeMessage: Record<number, string> = {
  200: "服务器成功返回请求的数据。",
  201: "新建或修改数据成功。",
  202: "一个请求已经进入后台排队（异步任务）。",
  204: "删除数据成功。",
  400: "发出的请求有错误，服务器没有进行新建或修改数据的操作。",
  401: "用户没有权限（令牌、用户名、密码错误）。",
  403: "用户得到授权，但是访问是被禁止的。",
  404: "发出的请求针对的是不存在的记录，服务器没有进行操作。",
  406: "请求的格式不可得。",
  410: "请求的资源被永久删除，且不会再得到的。",
  422: "当创建一个对象时，发生一个验证错误。",
  500: "服务器发生错误，请检查服务器。",
  502: "网关错误。",
  503: "服务不可用，服务器暂时过载或维护。",
  504: "网关超时。",
};

export function fetchRequest(url: string, params: any, headers?: any) {
  return Promise.race([
    fetch(url, {
      method: "post",
      body: JSON.stringify(params),
      mode: "cors",
      headers: headers
        ? headers
        : {
            "Accept-type": "application/json",
            "Content-type": "application/json;charset=utf-8",
            token: cookie.load("collegeToken"),
          },
    }),
    new Promise(function (resolve, reject) {
      setTimeout(() => reject(new Error("请求超时")), 60 * 1000);
    }),
  ])
    .then(checkStatus)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== undefined && json.code === errorCode.NO_PERMISSION) {
        window.location.hash = "#/wisdomCollegeView/nopermission";
        // window.location.pathname = "/wisdomCollegeView/nopermission";
      } else if (
        json.code !== undefined &&
        json.code === errorCode.LOGIN_OUT_DATE
      ) {
        window.location.hash = "#/wisdomCollegeView/nologin";
        // window.location.pathname = "/wisdomCollegeView/nologin";
      }
      return json;
    });
}

export function loginFetch(url: string, params: any) {
  return Promise.race([
    fetch(url, {
      method: "post",
      body: queryString.stringify(params),
      mode: "cors",
      headers: {
        "Accept-type": "application/json",
        "Content-type": "application/x-www-form-urlencoded;charset=utf-8",
      },
    }),
    new Promise(function (resolve, reject) {
      setTimeout(() => reject(new Error("请求超时")), 20000);
    }),
  ])
    .then(checkStatus)
    .then((res) => res.json())
    .then((json) => {
      return json;
    });
}

//检查返回的状态
function checkStatus(response: any) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText;
    history.push(`/error?error=${encodeURI(response.status)}`);
    const error = new Error(errorText);
    throw error;
  } else if (!response) {
    const errorText = "您的网络发生异常,无法连接服务器";
    const error = new Error(errorText);
    throw error;
  }

  return response;
}

//获取验证码
export function fetchImageCode(url: string) {
  return Promise.race([
    fetch(url, {
      method: "get",
      mode: "cors",
      headers: {
        "Accept-type": "application/json",
        "Content-type": "application/json;charset=utf-8",
      },
    }),
    new Promise(function (resolve, reject) {
      setTimeout(() => reject(new Error("请求超时")), 20000);
    }),
  ])
    .then(checkStatus)
    .then((res) => res.json());
}

//修改密码调用的接口
export function modifyFetch(url: string, params: any) {
  return Promise.race([
    fetch(url, {
      method: "post",
      body: JSON.stringify(params),
      mode: "cors",
      headers: {
        "Accept-type": "application/json",
        "Content-type": "application/json;charset=utf-8",
      },
    }),
    new Promise(function (resolve, reject) {
      setTimeout(() => reject(new Error("请求超时")), 20000);
    }),
  ])
    .then(checkStatus)
    .then((response) => response.json());
}

//退出接口
export function logoutFetch(url: string) {
  return Promise.race([
    fetch(url, {
      method: "post",
      mode: "cors",
      headers: {
        "Accept-type": "application/json",
        "Content-type": "application/json;charset=utf-8",
        token: cookie.load("collegeToken"),
      },
    }),
    new Promise(function (resolve, reject) {
      setTimeout(() => reject(new Error("请求超时")), 20000);
    }),
  ])
    .then(checkStatus)
    .then((response) => response.json());
}

//下载操作

export function downLoad(url: any) {
  return fetch(url, {
    method: "post",

    // body: JSON.stringify(params),

    headers: {
      "Content-type": "application/json;charset=UTF-8",

      token: cookie.load("collegeToken"),
    },
  }).then((res) => {
    return res.blob();
  });
}

export function getQueryString(url: string, name: string) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = url.substr(1).match(reg);

  if (r != null) return r[2];
  return "";
}
